package org.lex.net.proxy;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;

import org.lex.net.Password;
import org.lex.utils.Codec;


public class ProxyServer {
	public static final ProxyServer DIRECT;
	static {
		DIRECT = new ProxyServer("Direct", Proxy.NO_PROXY);
	}

	private String name = "";
	private Proxy proxy = null;
	private Password password = Password.NONE;

	public ProxyServer(String name, Proxy proxy) {
		this.name = name;
		this.proxy = proxy;
	}

	public ProxyServer(String name, Proxy.Type type, SocketAddress addr) {
		this(name, new Proxy(type, addr));
	}

	public ProxyServer(String name, Proxy.Type type, String host, int port) {
		this(name, type, new InetSocketAddress(host, port));
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Proxy getProxy() {
		return proxy;
	}

	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

	public Password getPassword() {
		return password;
	}

	public void setPassword(Password password) {
		this.password = password;
	}

	// convient method on Proxy class
	public String getHost() {
		if (null == proxy.address())
			return "";
		InetSocketAddress addr = (InetSocketAddress) proxy.address();
		if (addr.isUnresolved())
			return addr.getHostName();
		else
			return addr.getAddress().getHostAddress();
	}

	public Proxy.Type getType() {
		if (null == proxy) {
			return Proxy.Type.DIRECT;
		} else {
			return proxy.type();
		}
	}

	public int getPort() {
		if (null == proxy.address())
			return 0;
		return ((InetSocketAddress) proxy.address()).getPort();
	}

	public String toString() {
		StringBuilder buf = new StringBuilder();
		buf.append(name).append('=');
		buf.append(Codec.encodeProxy(proxy));
		return buf.toString();
	}
}
